package com.py.credit.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.py.credit.dao.SzjgDao;
import com.py.credit.entity.ConcernedSubject;
import com.py.credit.entity.Xyjg;
import com.py.credit.entity.XyjgDrqy;
import com.py.credit.entity.XyjgDrqydf;
import com.py.credit.service.SzjgService;
import com.py.credit.utils.SQLBuilder;
import com.py.framework.core.common.Page;

@Service
public class SzjgServiceImpl implements SzjgService {

	@Autowired
	private SzjgDao szjgao;

	@Override
	public List<Map<String, Object>> getByConditionForPage(String rank, String modelId, List<String> columns,
			String[] additionalColumns, String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = szjgao.selectByConditionForPage(rank, modelId, columns, additionalColumns,
				conditions, page);

		return batchLogs;
	}

	@Override
	public List<Map<String, Object>> get2ByConditionForPage(String rank, List<String> columns,
			String[] additionalColumns, String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = szjgao.select2ByConditionForPage(rank, columns, additionalColumns,
				conditions, page);

		return batchLogs;
	}

	public Map<String, Object> getModelByOffice(String ywId, String officeId) {
		return szjgao.getModelByOffice(ywId, officeId);
	}

	public List<Map<String, Object>> getByDrqyConditionForPage(String name, String startTime, String endTime,
			String userId, String deptId, String areaId, List<String> columns, String[] additionalColumns,
			String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = szjgao.getByDrqyConditionForPage(name, startTime, endTime, userId, deptId,
				areaId, columns, additionalColumns, conditions, page);
		return batchLogs;
	}

	public List<String> getBumeng(String ywId) {
		return szjgao.getBumeng(ywId);
	}

	public List<String> getDengjiByModel(String modelId) {
		return szjgao.getDengjiByModel(modelId);
	}

	public void addQy(CommonsMultipartFile file, String userId, String name, String deptId, String areaId,String officeName,String allParentId,String userName)
			throws Exception {
		Sheet st = readExcelFileForSheet(file.getInputStream());

		Map<String, Integer> result = new HashMap<String, Integer>();
		boolean reStart = true;
		int i = 0;
		List<Map<String, Object>> listDataMap = null;
		XyjgDrqy xyjgDrqy = new XyjgDrqy();
		xyjgDrqy.setUserId(userId);
		xyjgDrqy.setName(name);
		xyjgDrqy.setDeptId(deptId);
		xyjgDrqy.setAreaId(areaId);
		xyjgDrqy.setOfficeName(officeName);
		xyjgDrqy.setUserName(userName);
		String topDeptId = null;
		if(allParentId == null || "".equals(allParentId)){
			topDeptId = String.valueOf(deptId);
		}else{
			String[] alls = allParentId.split(",");
			topDeptId = alls[0];
		}
		xyjgDrqy.setTopDeptId(topDeptId);
		szjgao.addXyjgDrqy(xyjgDrqy);
		int start = 0;
		int end = 0;
		while (reStart) {
			start = i * 1000;
			end = (i + 1) * 1000;
			if (end > st.getLastRowNum()) {
				end = st.getLastRowNum();
			}

			listDataMap = readExcelData(start, end, st);
			int size = listDataMap.size();
			if (listDataMap.isEmpty()) {
				reStart = false;
			} else {

				for (Map<String, Object> map : listDataMap) {

					// if (map.get("name") != null &&
					// existInUnqiue(map.get("name").toString())
					// && !exsit(map.get("name").toString(), userId))
					if (null != map.get("name") && !"".equals(map.get("name"))) {
						szjgao.addXyjgDrqyQy(String.valueOf(map.get("name")), String.valueOf(xyjgDrqy.getId()));
					}
				}
			}
			i++;
		}
	}

	private Sheet readExcelFileForSheet(InputStream inputStream) throws IOException {
		Workbook wb = new XSSFWorkbook(inputStream);
		Sheet st = wb.getSheetAt(0);
		wb.close();
		return st;
	}

	private List<Map<String, Object>> readExcelData(int start, int end, Sheet st) {
		// 第一,二行为标题，不取
		Row row = null;
		int length = 0;
		Map<String, Object> map = null;
		Cell cell = null;
		String value = null;

		String[] cloumn = new String[] { "name" };
		length = st.getLastRowNum();

		if (end > length) {
			end = length;
		}
		List<Map<String, Object>> listDataMap = new LinkedList<>();
		for (int rowIndex = start + 1; rowIndex <= end; rowIndex++) {
			row = st.getRow(rowIndex);
			if (row == null) {
				continue;
			}

			short lastCellNum = row.getLastCellNum();

			boolean emptyRow = true;

			for (int cellIndex = 0; cellIndex <= lastCellNum; cellIndex++) {

				if (row.getCell(cellIndex, Row.RETURN_BLANK_AS_NULL) != null) {

					row.getCell(cellIndex).setCellType(HSSFCell.CELL_TYPE_STRING);

					if (!"".equals(row.getCell(cellIndex).getStringCellValue().trim())) {
						{

							emptyRow = false;
							break;
						}
					}

				}
			}

			if (emptyRow) {

				continue;
			}
			map = new HashMap<String, Object>();
			for (int i = 0; i < lastCellNum; i++) {
				value = "";
				cell = row.getCell(i);
				if (cell != null) {
					// 注意：一定要设成这个，否则可能会出现乱码
					switch (cell.getCellType()) {
					case HSSFCell.CELL_TYPE_STRING:
						value = cell.getStringCellValue().trim();
						break;
					case HSSFCell.CELL_TYPE_BLANK:
						break;

					default:
						value = "";
					}
				}
				map.put(cloumn[i], value);
				map.put("rowIndex", rowIndex + 1);
			}
			/* 把数据添加到List里面 */
			listDataMap.add(map);
		}

		return listDataMap;
	}

	public List<Map<String, Object>> getByDrqydf(String modelId, String id, String ranks,String startfen,String endfen) {
			
	    String[] list=  ranks.split(",");
		
		return szjgao.getByDrqydf(modelId, id,ranks,startfen,endfen,list);
	}

	public List<Map<String, Object>> get2ByDrqydf(String id, String ranks,String startfen,String endfen)  {
	
		 String[] list=  ranks.split(",");
		
		return szjgao.get2ByDrqydf(id,ranks,startfen,endfen,list);
	}
	
	public  Long addXyjg(String drId, String yongtu){
		Xyjg xyjg = new Xyjg();
		xyjg.setDrId(drId);
		xyjg.setYongtu(yongtu);
		szjgao.addXyjg(xyjg);
		return xyjg.getId();
	}
	
	public void addXyjgqy(XyjgDrqydf xyjgDrqydf,String id){
		XyjgDrqydf newXyjgDrqydf = new XyjgDrqydf();
		newXyjgDrqydf.setDrId(xyjgDrqydf.getDrId());
		newXyjgDrqydf.setDrqyId(xyjgDrqydf.getId());
		newXyjgDrqydf.setQymc(xyjgDrqydf.getQymc());
		newXyjgDrqydf.setRank(xyjgDrqydf.getRank());
		newXyjgDrqydf.setScore(xyjgDrqydf.getScore());
		newXyjgDrqydf.setTyshxydm(xyjgDrqydf.getTyshxydm());
		newXyjgDrqydf.setXypjId(id);
		
		szjgao.addXyjgqy(newXyjgDrqydf);
	}
	
	public List<Map<String, Object>> getByXyjgConditionForPage(String id,String name,String startTime,String endTime,
			String userId, String deptId, String areaId, List<String> columns, String[] additionalColumns,
			String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = szjgao.getByXyjgConditionForPage(id,  name, startTime, endTime,userId, deptId,
				areaId, columns, additionalColumns, conditions, page);
		return batchLogs;
	}
	
	public List<Map<String, Object>> getByXyjgqyConditionForPage(String id, List<String> columns, String[] additionalColumns,
			String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = szjgao.getXyjgqyByConditionForPage(id, columns, additionalColumns, conditions, page);
		return batchLogs;
	}
	
	public List<Map<String, Object>> getByXyjgtjConditionForPage(String deptId,String yongtu, List<String> columns, String[] additionalColumns,
			String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = szjgao.getXyjgtjByConditionForPage(deptId,yongtu, columns, additionalColumns, conditions, page);
		return batchLogs;
	}
	
	public List<Map> getLhcj(String ztmc,String bm,String type){
		return szjgao.getLhcj( ztmc, bm, type);
	}


}
